
package com.example.cia.support;

import com.example.cia.service.Service;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

public class HttpService<T> {
	
	/**
	 * 用于执行简单查询返回数据的操作
	 * 使用的是http get方法。
	 */
	
	/**
	 * T 可代表Integer类型的ID
	 * 或是String类型的文字
	 */
	private T data;
	
	/**
	 * url 访问的链接
	 */
	private String url;
	
	/**
	 * result 请求返回结果
	 */
	private String result;
	
	/**
	 * 域名 默认域名 不可修改
	 */
	private final String spaceName = "http://192.168.31.159:8080";
	
	private OkHttpClient okHttpClient;
	
	/**
	 * 所有服务表示
	 */
	private Service service;
	
	
	public Service getService() {
		return service;
	}


	
	public void setService(Service service) {
		this.service = service;
	}

	private Request request;	
	
	public T getData() {
		return data;
	}

	
	public void setData(T data) {
		this.data = data;
	}

	
	public String getUrl() {
		return url;
	}
	
	public String getResult(){
		return result;
	}

	
	public void setUrl(String url) {
		this.url = url;
	}

	//用于单一数据的传输
	public void doHttpGet(){
		okHttpClient = new OkHttpClient();
		request = new Request.Builder().url(spaceName+url+"?data="+data).build();

		okHttpClient.newCall(request).enqueue(new Callback(){

			@Override
			public void onFailure(Request request, IOException e) {
				// TODO Auto-generated method stub
				result = "0";

			}

			@Override
			public void onResponse(final Response response) throws IOException {
				// TODO Auto-generated method stub
				if(response.isSuccessful()){
					String rs = response.body().string();
					result = rs;
				}else{
					throw new IOException("Unexpected code "+response);
				}
				service.setFlag(true);
			}
			
		});

	}
	
	//用于多个数据的传输,具体数据在detailedQuery中自改
	public void doHttpGet(String detailedQuery){
		okHttpClient = new OkHttpClient();
		request = new Request.Builder().url(spaceName+url+"?"+detailedQuery).build();

		okHttpClient.newCall(request).enqueue(new Callback(){

			@Override
			public void onFailure(Request request, IOException e) {
				// TODO Auto-generated method stub
				result = "0";

			}

			@Override
			public void onResponse(final Response response) throws IOException {
				// TODO Auto-generated method stub
				if(response.isSuccessful()){
					String rs = response.body().string();
					result = rs;
				}else{
					throw new IOException("Unexpected code "+response);
				}
				service.setFlag(true);
			}
			
		});

	}

}
